package com.songlanyun.modules.marketing.seckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.songlanyun.common.enums.MarketingConstant;
import com.songlanyun.common.exception.RRException;
import com.songlanyun.common.utils.BeanUtil;
import com.songlanyun.common.utils.DateUtils;
import com.songlanyun.common.utils.custom.DateCustomUtils;
import com.songlanyun.modules.exception.MarketingException;
import com.songlanyun.modules.marketing.seckill.dao.SeckillActivityDao;
import com.songlanyun.modules.marketing.seckill.entity.SeckillActivity;
import com.songlanyun.modules.marketing.seckill.entity.SeckillActivityTimeItem;
import com.songlanyun.modules.marketing.seckill.model.dto.SeckillActivityDTO;
import com.songlanyun.modules.marketing.seckill.model.vo.SeckillActivityGoodsVO;
import com.songlanyun.modules.marketing.seckill.service.SeckillActivityGoodsService;
import com.songlanyun.modules.marketing.seckill.service.SeckillActivityService;
import com.songlanyun.modules.marketing.seckill.service.SeckillActivityTimeItemService;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.songlanyun.common.utils.PageUtils;
import com.songlanyun.common.utils.Query;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("marketingSeckillActivityService")
public class SeckillActivityServiceImpl extends ServiceImpl<SeckillActivityDao, SeckillActivity> implements SeckillActivityService {

    @Resource
    private SeckillActivityTimeItemService seckillActivityTimeItemService;

    @Resource
    private SeckillActivityGoodsService seckillActivityGoodsService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        IPage<SeckillActivity> page = this.baseMapper.seckillPage(new Query<SeckillActivity>().getPage(params), params);
        page.getRecords().forEach(s->{
            s.loadWeekTransform();
            s.loadActiveTimeState();//活动状态
        });
        return new PageUtils(page);
    }

    /**
     * 保存秒杀活动
     *
     * @param dto
     */
    @Override
    @Transactional
    public SeckillActivity saveSeckill(SeckillActivityDTO dto) {

        //保存秒杀活动
        SeckillActivity seckillActivity = new SeckillActivity();
        //保存秒杀活动日期信息
        Integer cycleMode = dto.getCycleMode();//周期方式

        //保存秒杀活动日期信息
        //获取起止时间的日期集合
        List<Date> betweenDates = DateCustomUtils.getBetweenDates(dto.getStartTime(), dto.getEndTime());

        List<Date> dateList = new ArrayList<Date>();//日期集合

        List<SeckillActivityTimeItem> list = new ArrayList<SeckillActivityTimeItem>();
        if (cycleMode.equals(MarketingConstant.CycleMode.EVERYDAY.getCode())) {
            //【每天】
            dateList = betweenDates;
        } else if (cycleMode.equals(MarketingConstant.CycleMode.EVERY_WEEK.getCode())) {
            //【每周】
            List<Integer> weekList = dto.getWeekList();
            Collections.sort(weekList);

            //查询起止日期在周几的所有记录
            dateList = DateCustomUtils.getBetweenDates(betweenDates, weekList);
        } else {
            throw new RRException(MarketingException.CYCLE_TYPE_ERROR);
        }

        //秒杀活动时间填写错误
        if (dateList.size() == 0) {
            throw new RRException(MarketingException.SECKILL_ACTIVITY_ERROR);
        }

        //保存或更新
        seckillActivity.setCycleMode(MarketingConstant.CycleMode.getByCode(dto.getCycleMode()));//周期方式//Integer转枚举
        BeanUtil.copyPropertiesIgnoreNull(dto, seckillActivity); //拷贝
        this.saveOrUpdate(seckillActivity);

        // 生成活动日期信息
        for (Date d : dateList) {

            int weekOfDate = DateCustomUtils.getWeekOfDate(d);//周几
            SeckillActivityTimeItem timeItem = seckillActivityTimeItemService.setTimeItem(seckillActivity, d, weekOfDate);

            //判断该商家在日期时间内有没有创建过活动，创建过则不能在创建
            seckillActivityTimeItemService.verifySeckillActivity(timeItem);

            list.add(timeItem);
        }

        //批量保存
        seckillActivityTimeItemService.saveBatch(list);

        return seckillActivity;

    }

    @Override
    public SeckillActivity getInfoById(Long id) {
        //秒杀活动
        SeckillActivity seckillActivity = this.getById(id, true);
        //秒杀活动日期时间
        seckillActivity.loadTimeItemList();
        return seckillActivity;
    }

    @Override
    public SeckillActivity getById(Long id, Boolean isThrow) {
        SeckillActivity seckillActivity = this.baseMapper.selectOne(
                new LambdaQueryWrapper<SeckillActivity>()
                        .eq(SeckillActivity::getId, id)
        );

        if (seckillActivity == null) {
            if (isThrow) {
                throw new RRException(MarketingException.SECKILL_ACTIVITY_NOT_EXIST);
            }
        }

        return seckillActivity;
    }

    @Override
    @Transactional
    public void updateSeckill(SeckillActivityDTO dto) {
        //先删除之前保存的活动日期时间记录
        boolean remove = seckillActivityTimeItemService.removeBySeckillId(dto.getId());

        if (remove) {
            //再保存
            saveSeckill(dto);
        }

    }

    @Override
    public SeckillActivity getByShopIdAndId(Long shopId, Long seckillId, boolean b) {
        SeckillActivity one = this.baseMapper.selectOne(
                new LambdaQueryWrapper<SeckillActivity>()
                        .eq(SeckillActivity::getId, seckillId)
                        .eq(SeckillActivity::getShopId, shopId)
                        .last("limit 1")
        );
        if (one == null) {
            if (b) {
                throw new RRException(MarketingException.SECKILL_ACTIVITY_NOT_EXIST);
            }
        }
        return one;
    }

    @Override
    public List<SeckillActivity> getShopSeckillList(Long shopId) {
        return this.baseMapper.selectList(
                new LambdaQueryWrapper<SeckillActivity>()
                        .eq(SeckillActivity::getShopId, shopId)
        );
    }

    @Override
    public Long finishTime(Long shopId) {

        //当前商家正在进行的活动
        SeckillActivity seckillActivity = this.baseMapper.getNowShopActivity(shopId);
        Long finishTime = 0L; //结束时间秒值
        if (seckillActivity != null) {

            try {
                //当天的结束时间
                Date date = DateUtils.stringToDate(DateCustomUtils.dateToString(new Date()) + " " + seckillActivity.getEndHour());
                if (date != null) {
                    finishTime = date.getTime() / 1000;
                }
            } catch (Exception e) {
                return null;
            }
        }
        return finishTime;
    }

    @Override
    @Transactional
    public void delById(Long id) {
        //校验该秒杀中是否有秒杀商品
        seckillActivityGoodsService.verifyActiveGoods(id);

        //删除秒杀
        this.baseMapper.deleteById(id);
        //删除秒杀时间段
        seckillActivityTimeItemService.removeBySeckillId(id);
    }


}
